<template>
  <div>
    <canvas :id="id" width="200" height="150"></canvas>
  </div>
</template>
<script setup lang="ts">
const props = defineProps({
  v: {
    type: Number,
    default: 0.2,
  },
})
const id = computed(() => {
  return `canvasBox${Math.random()}`
})

const initCanvas = () => {
  const myCanvas = document.getElementById(id.value) as HTMLElement
  const ctx = (myCanvas as any).getContext('2d')
  ctx.globalCompositeOperation = 'xor'
  // 两个椭圆 + 一个矩形

  // 圆柱体顶部椭圆中心点及圆柱体高
  const x = 50
  const y = 35
  const h = 80
  const xRadius = 40
  const yRadius = 20
  const currentV = computed(() => {
    return props.v * (h as number)
  })
  // 水位的高度
  const fillHeight = currentV.value

  // 第二个椭圆
  ctx.beginPath()
  ctx.ellipse(x, y + h, xRadius, yRadius, 0, 0, Math.PI * 2)
  ctx.fillStyle = 'rgba(0,255,255,0.5)'
  ctx.strokeStyle = 'grey'
  ctx.fill()
  ctx.stroke()

  // 线条
  ctx.beginPath()
  ctx.moveTo(x - xRadius, y)
  ctx.lineTo(x - xRadius, y + h)
  ctx.stroke()

  // 线条
  ctx.beginPath()
  ctx.moveTo(x + xRadius, y)
  ctx.lineTo(x + xRadius, y + h)
  ctx.stroke()

  // 水位矩形
  ctx.beginPath()
  ctx.moveTo(x - xRadius, y + h - fillHeight)
  ctx.lineTo(x + xRadius, y + h - fillHeight)
  ctx.lineTo(x + xRadius, y + h)
  ctx.lineTo(x - xRadius, y + h)
  ctx.moveTo(x - xRadius, y + h - fillHeight)
  ctx.fillStyle = 'rgba(0,255,255,0.5)'
  ctx.strokeStyle = 'transparent'
  ctx.fill()
  ctx.stroke()

  ctx.globalCompositeOperation = 'destination-out'

  // 水位椭圆
  ctx.beginPath()
  ctx.ellipse(x, y + h - fillHeight, xRadius - 5, yRadius - 5, 0, 0, Math.PI * 2)
  ctx.fillStyle = 'rgba(0,255,255,1)'
  ctx.strokeStyle = 'rgba(128,128,128,0.5)'
  ctx.fill()
  ctx.stroke()

  ctx.globalCompositeOperation = 'xor'
  ctx.beginPath()
  ctx.ellipse(x, y + h - fillHeight, xRadius, yRadius, 0, 0, Math.PI * 2)
  ctx.fillStyle = 'rgba(0,255,255,0.5)'
  ctx.strokeStyle = 'rgba(128,128,128,0.5)'
  ctx.fill()
  ctx.stroke()

  // 第一个椭圆
  ctx.ellipse(x, y, xRadius, yRadius, 0, 0, Math.PI * 2)
  ctx.fillStyle = 'transparent'
  ctx.strokeStyle = 'grey'
  ctx.fill()
  ctx.stroke()
}
onMounted(() => {
  initCanvas()
})
</script>
<style lang="less" scoped></style>
